<template>
  <div class="cart-page">
    <div class="cart-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>购物车</h2>
        <span class="cart-count">共{{ cartItems.length }}件商品</span>
      </div>

      <!-- 购物车内容 -->
      <div v-if="cartItems.length > 0" class="cart-content">
        <!-- 购物车头部 -->
        <div class="cart-header">
          <el-checkbox
              v-model="selectAll"
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
          >
            全选
          </el-checkbox>
          <span class="header-text">商品信息</span>
          <span class="header-text">单价</span>
          <span class="header-text">数量</span>
          <span class="header-text">小计</span>
          <span class="header-text">操作</span>
        </div>

        <!-- 购物车商品列表 -->
        <div class="cart-items">
          <div
              v-for="item in cartItems"
              :key="item.id"
              :class="{ disabled: item.productStatus === 0 || item.stock <= 0 }"
              class="cart-item"
          >
            <div class="item-select">
              <el-checkbox
                  v-model="item.selected"
                  :disabled="item.productStatus === 0 || item.stock <= 0"
                  @change="handleItemSelect"
              />
            </div>

            <div class="item-product" @click="goToProductDetail(item.productId)">
              <div class="product-image">
                <el-image
                    :alt="item.productName"
                    :src="item.productImage || '/placeholder.jpg'"
                    fit="cover"
                />
              </div>
              <div class="product-info">
                <h4 class="product-name">{{ item.productName }}</h4>
                <p v-if="item.productStatus === 0" class="product-status error">商品已下架</p>
                <p v-else-if="item.stock <= 0" class="product-status error">库存不足</p>
                <p v-else class="product-status">现货</p>
              </div>
            </div>

            <div class="item-price">
              <span class="current-price">¥{{ item.currentPrice }}</span>
              <span v-if="item.priceChanged" class="old-price">¥{{ item.cartPrice }}</span>
            </div>

            <div class="item-quantity">
              <el-input-number
                  v-model="item.quantity"
                  :disabled="item.productStatus === 0 || item.stock <= 0 || updating[item.id]"
                  :max="Math.min(99, item.stock)"
                  :min="1"
                  size="small"
                  @change="updateQuantity(item)"
              />
            </div>

            <div class="item-subtotal">
              <span class="subtotal-price">¥{{ item.subtotal }}</span>
            </div>

            <div class="item-actions">
              <el-button
                  :loading="removing[item.id]"
                  class="remove-btn"
                  type="text"
                  @click="removeItem(item.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 购物车底部 -->
        <div class="cart-footer">
          <div class="footer-left">
            <el-button :disabled="selectedItems.length === 0" @click="clearSelected">
              删除选中商品
            </el-button>
          </div>

          <div class="footer-right">
            <div class="total-info">
              <span class="total-text">
                已选择{{ selectedCount }}件商品（{{ selectedItems.length }}种），总计：
              </span>
              <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
            <el-button
                :disabled="selectedItems.length === 0"
                size="large"
                type="primary"
                @click="checkout"
            >
              去结算
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空购物车 -->
      <div v-else class="empty-cart">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="goShopping">去购物</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {batchRemoveCartItems, getCartList, removeCartItem, updateCartItem} from '@/api/cart'
import {useCartStore} from '@/store'

// 路由相关
const router = useRouter()

// 状态管理
const cartStore = useCartStore()

// 响应式数据
const loading = ref(false)
const cartItems = ref([])
const updating = reactive({})
const removing = reactive({})

// 全选状态
const selectAll = ref(false)
const isIndeterminate = ref(false)

// 计算属性
const selectedItems = computed(() => {
  return cartItems.value.filter(item =>
      item.selected && item.productStatus === 1 && item.stock > 0
  )
})

const selectedCount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + item.quantity
  }, 0)
})

const totalAmount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + parseFloat(item.subtotal || 0)
  }, 0)
})

// 获取购物车列表
const fetchCartList = async () => {
  try {
    loading.value = true
    const response = await getCartList()
    cartItems.value = response.data.map(item => ({
      ...item,
      selected: false
    }))
    updateSelectAllState()
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('获取购物车失败')
  } finally {
    loading.value = false
  }
}

// 更新全选状态
const updateSelectAllState = () => {
  const validItems = cartItems.value.filter(item => item.productStatus === 1 && item.stock > 0)
  const selectedValidItems = validItems.filter(item => item.selected)

  if (validItems.length === 0) {
    selectAll.value = false
    isIndeterminate.value = false
  } else if (selectedValidItems.length === validItems.length) {
    selectAll.value = true
    isIndeterminate.value = false
  } else if (selectedValidItems.length > 0) {
    selectAll.value = false
    isIndeterminate.value = true
  } else {
    selectAll.value = false
    isIndeterminate.value = false
  }
}

// 处理全选
const handleSelectAll = (checked) => {
  cartItems.value.forEach(item => {
    if (item.productStatus === 1 && item.stock > 0) {
      item.selected = checked
    }
  })
  updateSelectAllState()
}

// 处理单项选择
const handleItemSelect = () => {
  updateSelectAllState()
}

// 更新商品数量
const updateQuantity = async (item) => {
  if (item.quantity < 1 || item.quantity > Math.min(99, item.stock)) {
    return
  }

  try {
    updating[item.id] = true

    await updateCartItem(item.id, {
      quantity: item.quantity
    })

    ElMessage.success('数量更新成功')
    // 重新获取购物车列表以更新小计等数据
    await fetchCartList()
    // 更新购物车统计
    await cartStore.fetchCartSummary()
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败')
    // 恢复原数量
    await fetchCartList()
  } finally {
    updating[item.id] = false
  }
}

// 删除单个商品
const removeItem = async (itemId) => {
  try {
    await ElMessageBox.confirm('确定要删除这件商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    removing[itemId] = true

    await removeCartItem(itemId)

    ElMessage.success('商品已删除')
    await fetchCartList()
    await cartStore.fetchCartSummary()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  } finally {
    removing[itemId] = false
  }
}

// 删除选中商品
const clearSelected = async () => {
  if (selectedItems.value.length === 0) {
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的${selectedItems.value.length}件商品吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const cartIds = selectedItems.value.map(item => item.id)

    await batchRemoveCartItems(cartIds)

    ElMessage.success('选中商品已删除')
    await fetchCartList()
    await cartStore.fetchCartSummary()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 去结算
const checkout = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  // 跳转到结算页面，传递选中的商品信息
  const selectedCartItems = cartItems.value.filter(item => item.selected)
  router.push({
    path: '/checkout',
    query: {
      items: JSON.stringify(selectedCartItems)
    }
  })
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 去购物
const goShopping = () => {
  router.push('/home')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCartList()
})
</script>

<style scoped>
.cart-page {
  background: var(--bg-secondary);
  min-height: 100vh;
  padding: 2rem;
}

.cart-container {
  max-width: 1200px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding: 1.5rem 2rem;
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-light);
}

.page-header h2 {
  margin: 0;
  color: var(--text-primary);
  font-weight: 700;
}

.cart-count {
  color: #909399;
  font-size: 14px;
}

/* 购物车内容 */
.cart-content {
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-light);
}

/* 购物车头部 */
.cart-header {
  display: grid;
  grid-template-columns: 60px 1fr 120px 120px 120px 80px;
  align-items: center;
  padding: 1rem 1.5rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-light);
  font-weight: 600;
  color: var(--text-secondary);
}

.header-text {
  text-align: center;
}

/* 购物车商品列表 */
.cart-items {
  max-height: 600px;
  overflow-y: auto;
}

.cart-item {
  display: grid;
  grid-template-columns: 60px 1fr 120px 120px 120px 80px;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-light);
  transition: all 0.3s ease;
}

.cart-item:hover {
  background: var(--primary-50);
}

.cart-item.disabled {
  opacity: 0.6;
  background: #f9f9f9;
}

.item-select {
  display: flex;
  justify-content: center;
}

.item-product {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding-right: 20px;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #303133;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-status {
  font-size: 12px;
  margin: 0;
  color: #67c23a;
}

.product-status.error {
  color: #f56c6c;
}

.item-price,
.item-subtotal {
  text-align: center;
}

.current-price,
.subtotal-price {
  font-size: 16px;
  font-weight: 500;
  color: #e6a23c;
}

.old-price {
  color: #909399;
  font-size: 12px;
  text-decoration: line-through;
  margin-left: 8px;
}

.item-quantity {
  display: flex;
  justify-content: center;
}

.item-actions {
  text-align: center;
}

.remove-btn {
  color: #f56c6c;
}

.remove-btn:hover {
  color: #f56c6c;
}

/* 购物车底部 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fafafa;
  border-top: 1px solid #e4e7ed;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  font-size: 16px;
}

.total-text {
  color: #606266;
}

.total-price {
  font-size: 20px;
  font-weight: bold;
  color: #e6a23c;
  margin-left: 10px;
}

/* 空购物车 */
.empty-cart {
  background: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-page {
    padding: 1rem;
  }

  .page-header {
    padding: 1rem;
    margin-bottom: 1rem;
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .page-header h2 {
    font-size: 1.25rem;
  }

  .cart-header {
    display: none;
  }

  .cart-item {
    display: flex;
    flex-direction: column;
    padding: 1rem;
    gap: 1rem;
    position: relative;
  }

  .cart-item .el-checkbox {
    position: absolute;
    top: 1rem;
    left: 1rem;
    z-index: 2;
  }

  .item-product {
    display: flex;
    gap: 1rem;
    margin-left: 2rem; /* 为复选框留空间 */
    cursor: pointer;
  }

  .product-image {
    width: 80px;
    height: 80px;
    flex-shrink: 0;
  }

  .product-info {
    flex: 1;
  }

  .product-name {
    font-size: 0.875rem;
    line-height: 1.4;
    margin-bottom: 0.5rem;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .product-status {
    font-size: 0.75rem;
    margin: 0;
  }

  .item-price,
  .item-quantity,
  .item-subtotal {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 1rem;
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    margin: 0 2rem;
  }

  .item-price::before {
    content: '单价：';
    font-size: 0.875rem;
    color: var(--text-secondary);
  }

  .item-quantity::before {
    content: '数量：';
    font-size: 0.875rem;
    color: var(--text-secondary);
  }

  .item-subtotal::before {
    content: '小计：';
    font-size: 0.875rem;
    color: var(--text-secondary);
  }

  .item-quantity .el-input-number {
    width: 100px;
  }

  .item-actions {
    margin: 0 2rem;
    display: flex;
    gap: 0.5rem;
  }

  .item-actions .el-button {
    flex: 1;
    font-size: 0.875rem;
  }

  .cart-footer {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
    padding: 1rem;
    margin-top: 1rem;
  }

  .footer-left {
    order: 2;
    justify-content: center;
  }

  .footer-right {
    order: 1;
    flex-direction: column;
    gap: 1rem;
  }

  .total-info {
    text-align: center;
    padding: 1rem;
    background: var(--bg-secondary);
    border-radius: var(--radius-lg);
  }

  .total-amount {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--primary-color);
  }

  .checkout-btn {
    width: 100%;
    padding: 0.75rem;
    font-size: 1rem;
    font-weight: 600;
  }
}

@media (max-width: 480px) {
  .cart-item {
    position: relative;
    padding: 15px 15px 15px 50px;
  }

  .product-image {
    width: 50px;
    height: 50px;
  }

  .product-name {
    font-size: 13px;
  }

  .item-price,
  .item-quantity,
  .item-subtotal {
    display: block;
    margin-bottom: 8px;
    text-align: left;
  }

  .item-price::before {
    content: '单价：';
    color: #909399;
  }

  .item-subtotal::before {
    content: '小计：';
    color: #909399;
  }
}
</style>
